import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;


public class ChannelCopy {

	public static void main(String[] args) throws IOException {
		ReadableByteChannel in = Channels.newChannel(System.in);
		WritableByteChannel out = Channels.newChannel(System.out);
		copyChannel(in,out);
		System.out.println("copy1");
//		copyChannel2(in,out);
//		System.out.println("copy2");
		in.close();
		out.close();
	}

	private static void copyChannel2(ReadableByteChannel src, WritableByteChannel dest) throws IOException {

		ByteBuffer buffer = ByteBuffer.allocate(1024);
		while(src.read(buffer) > 0 ){
			buffer.flip();
			dest.write(buffer);
			buffer.compact();
		}

		buffer.flip();
		while(buffer.hasRemaining()){
			dest.write(buffer);
		}

	}

	private static void copyChannel(ReadableByteChannel src, WritableByteChannel dest) throws IOException {

		ByteBuffer buffer = ByteBuffer.allocate(1024);
		while(src.read(buffer) > 0 ){
			buffer.flip();
			while(buffer.hasRemaining()){
				dest.write(buffer);
			}
			buffer.clear();
		}

	}

}
